package com.fce.fcesystem.controller;

import com.fce.fcesystem.ex.*;
import com.fce.fcesystem.utils.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * @Description: 控制器的基类，用来处理异常
 */
public class BaseController {
    //操作成功，设置一个200状态码
    public static final int OK = 200;

    public static final int USER_NOT_EXIT = 2001;

    public static final int KEY_ALRED_EXIT = 2002;

    public static final int SMS_SEND_FAILED = 2003;

    public static final int KEY_CODE_ERROR = 2004;

    public static final int PASS_INCORRECT = 2005;
    //@ExceptionHandler用于统一处理方法抛出的异常
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicateException) {
            result.setState(4000);
        } else if (e instanceof InsertException) {
            result.setState(4001);
        }else if (e instanceof UserNotFoundException) {
            result.setState(4002);
        }else if (e instanceof PasswordNotMatchException){
            result.setState(4003);
        }else if (e instanceof UpdateException){
            result.setState(4004);
        }else if (e instanceof CodeException){
            result.setState(4005);
        }else if (e instanceof DeleteException){
            result.setState(4006);
        }else if (e instanceof IsbnDuplicateException){
            result.setState(4007);
        }else if (e instanceof UpdateBookException){
            result.setState(4008);
        }else if (e instanceof SendMailException){
            result.setState(4009);
        }else if (e instanceof KeyException){
            result.setState(4010);
        }
        return result;
    }

    /**
     * @description:从session对象中取出用户id
     **/
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    /**
     * @description:从session对象中取出用户名
     **/
    protected final String getUnameFromSession(HttpSession session){
        return session.getAttribute("uname").toString();
    }
}

